package binarytree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 14:44
 * https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
 * 给定一个二叉树，找出其最小深度。
 */
public class MinDepth {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 层次遍历
     * @param root
     * @return
     */
    public int minDepth1(TreeNode root) {
        Queue<TreeNode> levelNodes = new LinkedList<>();
        int min = 0;
        if (root != null) {
            levelNodes.offer(root);
        }
        while (!levelNodes.isEmpty()) {
            min++;
            int size = levelNodes.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = levelNodes.poll();
                if (poll.left == null && poll.right == null) {
                    return min;
                }
                if (poll.left != null) {
                    levelNodes.offer(poll.left);
                }
                if (poll.right != null) {
                    levelNodes.offer(poll.right);
                }
            }
        }
        return min;
    }


    /**
     * dfs
     * @param root
     * @return
     */
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int minDeepth = Integer.MAX_VALUE;
        //防止left为空，返回0，为空时不需要计算
        if (root.left != null) {
            minDeepth = Math.min(Integer.MAX_VALUE, minDepth(root.left));
        }
        if (root.right != null) {
            minDeepth = Math.min(minDeepth, minDepth(root.right));
        }
        return minDeepth + 1;
    }

    public static void main(String[] args) {

    }
}
